/*
 * @Descripttion:
 * @LastEditors: chen.long
 * @LastEditTime: 2024-02-24 13:49:10
 */
import { YBMICRO_APP_ID, YBMICRO_SCRIPT_ID } from '../constant';

/**
 * @Author: chen.long
 * @Descripttion: 获取需要同步的url
 */
export function getSyncUrl(id: string): string {
  let winUrlElement = anchorElementGenerator(window.location.href);
  const queryMap = getAnchorElementQueryMap(winUrlElement);
  winUrlElement = null;
  const syncUrl = window.decodeURIComponent(queryMap[id] || '');
  return syncUrl;
}

/**
 * @Author: chen.long
 * @Descripttion: 根据id获取iframe
 * @Param:
 * @param {string} id iframe的id
 */
export function getIframe(id: string): HTMLIFrameElement {
  return window.document.querySelector(`iframe[${YBMICRO_APP_ID}="${id}"]`);
}

/**
 * @Author: chen.long
 * @Descripttion: 生成a元素
 * @Param:
 * @param {string} url 传给a元素的地址
 */
export function anchorElementGenerator(url: string): HTMLAnchorElement {
  const element = window.document.createElement('a');
  element.href = url;
  element.href = element.href; // hack ie
  return element;
}

/**
 * @Author: chen.long
 * @Descripttion: 获取a元素的查询参数
 * @Param:
 * @param {HTMLAnchorElement} anchorElement 元素节点
 */
export function getAnchorElementQueryMap(anchorElement: HTMLAnchorElement): {
  [key: string]: string;
} {
  const queryList = anchorElement.search.replace('?', '').split('&');
  const queryMap = {};
  queryList.forEach(query => {
    const [key, value] = query.split('=');
    if (key && value) queryMap[key] = value;
  });
  return queryMap;
}

/**
 * @Author: chen.long
 * @Descripttion: 给元素设置属性
 */
export function setAttrsToElement(
  element: HTMLElement,
  attrs: { [key: string]: any }
) {
  Object.keys(attrs).forEach(name => {
    element.setAttribute(name, attrs[name]);
  });
}

/**
 * @Author: chen.long
 * @Descripttion: 获取容器元素
 * @Param:
 * @param {string} container 容器元素选择器
 */
export function getContainer(container: string | HTMLElement): HTMLElement {
  return typeof container === 'string'
    ? (document.querySelector(container) as HTMLElement)
    : container;
}

/**
 * @Author: chen.long
 * @Descripttion: 判断传入的元素是否是脚本标签
 * @Param:
 * @param {HTMLElement} element 待判断的元素
 */
export function isScriptElement(element: HTMLElement): boolean {
  return element.tagName?.toUpperCase() === 'SCRIPT';
}

let count = 1;
/**
 * @Author: chen.long
 * @Descripttion: 给脚本标签设置tag
 * @Param:
 * @param {HTMLScriptElement} element 脚本标签元素
 * @param {string} tag tag
 */
export function setTagToScript(element: HTMLScriptElement, tag?: string): void {
  if (isScriptElement(element)) {
    const scriptTag = tag || String(count++);
    element.setAttribute(YBMICRO_SCRIPT_ID, scriptTag);
  }
}

/**
 * @Author: chen.long
 * @Descripttion: 获取元素上的tag
 * @Param:
 * @param {HTMLScriptElement} element 指定元素
 */
export function getTagFromScript(element: HTMLScriptElement): string | null {
  if (isScriptElement(element)) {
    return element.getAttribute(YBMICRO_SCRIPT_ID);
  }
  return null;
}
